package com.wyfan.scaffold.common.config.redis;

import cn.hutool.core.util.ZipUtil;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * redis 自定义序列化 -  字符串压缩存储
 */
public class ZlibRedisSerializer implements RedisSerializer<String> {

    private final Charset charset;
    public static final ZlibRedisSerializer US_ASCII;
    public static final ZlibRedisSerializer ISO_8859_1;
    public static final ZlibRedisSerializer UTF_8;

    public ZlibRedisSerializer() {
        this(StandardCharsets.UTF_8);
    }

    public ZlibRedisSerializer(Charset charset) {
        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
    }

    /**
     * 序列化
     */
    @Override
    public byte[] serialize(String str) throws SerializationException {
        return ZipUtil.zlib(str.getBytes(this.charset), 6);
    }

    /**
     * 反序列化
     */
    @Override
    public String deserialize(byte[] bytes) throws SerializationException {
        return bytes == null ? null : new String(ZipUtil.unZlib(bytes),charset);
    }


    static {
        US_ASCII = new ZlibRedisSerializer(StandardCharsets.US_ASCII);
        ISO_8859_1 = new ZlibRedisSerializer(StandardCharsets.ISO_8859_1);
        UTF_8 = new ZlibRedisSerializer(StandardCharsets.UTF_8);
    }
}
